<template>
  <el-card>
    <div slot="header">
      <span>{{ title }}</span>
    </div>
    <el-row>
      <ReportForm
        :disabled="isView"
        :colNumOfRow="2"
        :formData.sync="baseInfoForm"
        ref="baseInfoForm"
        refName="base-info-form"
        :formFields="BASE_INFO_FIELDS" />
    </el-row>
    <el-divider />
    <el-row>
      <el-tabs ref="tabs" type="card" v-model="activateName">
        <el-tab-pane label="基本信息" name="基本信息" v-if="showBasicInfo || showProductionInfo">
          <el-card>
            <el-divider v-if="showBasicInfo" content-position="left"><h4>基础信息</h4></el-divider>
            <ReportForm
              :disabled="isView"
              :formData.sync="basicInfoForm"
              ref="basicInfoForm"
              refName="basic-info-form"
              :formFields="filterFiles(BASIC_INFO_FIELDS)" />
            <el-divider v-if="showProductionInfo" content-position="left"><h4>生产信息</h4></el-divider>
            <ReportForm
              :disabled="isView"
              :formData.sync="productionInfoForm"
              ref="productionInfoForm"
              refName="production-info-form"
              :formFields="filterFiles(PRODUCTION_INFO_FIELDS)" />
          </el-card>
        </el-tab-pane>
        <el-tab-pane v-if="planInfo.targetList.includes(1)" label="人员信息" name="人员信息">
          <SupplyUserTable ref="supplyUserInfo" :isView="isView" :supplierUserList="supplierPersonList" />
        </el-tab-pane>
        <el-tab-pane v-if="showProducInfo" label="商品信息" name="商品信息">
          <el-card>
            <el-divider content-position="left"><h4>商品信息</h4></el-divider>
            <ReportForm
              :disabled="isView"
              :formData.sync="productInfoForm"
              ref="productInfoForm"
              refName="product-info-form"
              :formFields="filterFiles(PRODUCT_INFO_FIELDS)" />
          </el-card>
        </el-tab-pane>
        <el-tab-pane v-if="showManagementInfo" label="管理信息" name="管理信息">
          <el-card>
            <el-divider content-position="left"><h4>管理信息</h4></el-divider>
            <ReportForm
              :disabled="isView"
              :formData.sync="managementInfoForm"
              ref="managementInfoForm"
              refName="management-info-form"
              :formFields="filterFiles(MANAGEMENT_INFO_FIELDS)" />
          </el-card>
        </el-tab-pane>
        <el-tab-pane v-if="showBillingInfo || showFinancialInfo || showQualityInfo || showRebateInfo || showDeliveryInfo" label="合同信息" name="合同信息">
          <el-card>
            <el-divider v-if="showBillingInfo" content-position="left"><h4>结算信息</h4></el-divider>
            <ReportForm
              :disabled="isView"
              :formData.sync="billingInfoForm"
              ref="billingInfoForm"
              refName="billing-info-form"
              :formFields="filterFiles(CONTRACT_BILLING_INFO_FIELDS)" />
            <el-divider v-if="showBillingInfo" content-position="left"><h4>结算方式</h4></el-divider>
            <SettlementMethod v-if="showBillingInfo" id="billing-method-form" ref="billingMethodList" :showTitle="false" :dataSource="supplierSettlementList" @change="handleChange" />
            <ReportForm
              style="margin-top: 10px"
              :disabled="isView"
              :formData.sync="billingMethodInfoForm"
              ref="billingMethodInfoForm"
              refName="billing-method-info-form"
              :formFields="filterFiles(BILLING_METHOD_FIELDS)" />
            <el-divider v-if="showFinancialInfo" content-position="left"><h4>财务信息</h4></el-divider>
            <ReportForm
              :disabled="isView"
              :formData.sync="financialInfoForm"
              ref="financialInfoForm"
              refName="financial-info-form"
              :formFields="filterFiles(CONTRACT_FINANCIAL_INFO_FIELDS)" />
            <el-divider v-if="showFinancialInfo && isQualifiedSupplier" content-position="left"><h4>原材料信息</h4></el-divider>
            <RawMaterialInfo
              v-if="showFinancialInfo && isQualifiedSupplier"
              id="raw-material-info"
              ref="rawMaterialInfo"
              :dataSource="supplierRawMaterialList"
              :contractInfo="financialInfoForm || {}"
              @change="handleChange"
            />
            <el-divider v-if="showQualityInfo" content-position="left"><h4>铺底质保信息</h4></el-divider>
            <ReportForm
              :disabled="isView"
              :formData.sync="qualityInfoForm"
              ref="qualityInfoForm"
              refName="quality-info-form"
              :formFields="filterFiles(CONTRACT_QUALITY_INFO_FIELDS)" />
            <el-divider v-if="showRebateInfo" content-position="left"><h4>返利信息</h4></el-divider>
            <ReportForm
              :disabled="isView"
              :formData.sync="rebateInfoForm"
              ref="rebateInfoForm"
              refName="rebate-info-form"
              :formFields="filterFiles(CONTRACT_REBATE_INFO_FIELDS)" />
            <el-divider v-if="showDeliveryInfo" content-position="left"><h4>交付信息</h4></el-divider>
            <ReportForm
              :disabled="isView"
              :formData.sync="deliveryInfoForm"
              ref="deliveryInfoForm"
              refName="delivery-info-form"
              :formFields="filterFiles(CONTRACT_DELIVERY_INFO_FIELDS)" />
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </el-row>
    <el-row type="flex" justify="center" class="formFooter">
      <el-button v-if="!isView" type="primary" :loading="submitLoading" @click="handleValidSubmit(true)">提交</el-button>
      <el-button v-if="!isView" type="primary" :loading="submitLoading" @click="handleSubmit(false)">暂存</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </el-row>
  </el-card>
</template>
<script>
import ReportForm from './components/BaseForm' // 表单组件
import SupplyUserTable from './components/SupplyUserTable' // 人员信息
import SettlementMethod from '@/pages/supplier/components/settlementMethod' // 结算方式组件
import RawMaterialInfo from '@/pages/supplier/components/rawMaterialInfo' // 原材料信息组件
import {
  BASE_INFO_FIELDS,
  BASIC_INFO_FIELDS, // 基本信息 基础信息
  PRODUCTION_INFO_FIELDS, // 基本信息 生产信息
  PRODUCT_INFO_FIELDS, // 商品信息
  MANAGEMENT_INFO_FIELDS, // 管理信息
  CONTRACT_BILLING_INFO_FIELDS,
  BILLING_METHOD_FIELDS,
  CONTRACT_FINANCIAL_INFO_FIELDS,
  CONTRACT_QUALITY_INFO_FIELDS,
  CONTRACT_REBATE_INFO_FIELDS,
  CONTRACT_DELIVERY_INFO_FIELDS,
} from './constants/report'
import {
  querySupplierDetailService,
  queryReportDetailService,
  addReportService,
  stashReportService
} from '@api/supplier/returnVisteManage';
import { queryItemsByDictIdsService, querySysTypeByDictIdsService, queryManageAreaService, queryTodoTypeservice } from '@api/supplier/components';
import { isResponseSuccess } from '@/pages/supplier/utils/bizUtils';

export default {
  components: {
    ReportForm,
    SupplyUserTable,
    SettlementMethod,
    RawMaterialInfo
  },
  data () {
    return {
      reportId: null,
      supplierClassify: '', // 供应商类型
      submitLoading: false,
      tabList: ['基本信息', '人员信息', '商品信息', '管理信息', '合同信息'],
      activateName: '基本信息',
      BASE_INFO_FIELDS,
      BASIC_INFO_FIELDS,
      PRODUCTION_INFO_FIELDS,
      PRODUCT_INFO_FIELDS,
      MANAGEMENT_INFO_FIELDS,
      CONTRACT_BILLING_INFO_FIELDS,
      BILLING_METHOD_FIELDS,
      CONTRACT_FINANCIAL_INFO_FIELDS,
      CONTRACT_QUALITY_INFO_FIELDS,
      CONTRACT_REBATE_INFO_FIELDS,
      CONTRACT_DELIVERY_INFO_FIELDS,
      planInfo: {
        planId: '',
        supplierId: '',
        targetList: [],
        type: null
      },
      baseInfoForm: {
        visitTime: '',
        negotiationDetail: '',
        inspectCompleteTime: '',
        disposalMeasures: '',
        subsequentBacklog: [],
        backlogExplain: '',
        planCompleteTime: '',
      },
      basicInfoForm: {}, // 基础信息
      productionInfoForm: {}, // 生产信息
      productInfoForm: {}, // 商品信息
      managementInfoForm: {}, // 管理信息
      billingInfoForm: {}, // 结算信息
      billingMethodInfoForm: {}, // 结算方式form
      financialInfoForm: {}, // 财务信息
      qualityInfoForm: {}, // 铺底质保信息
      rebateInfoForm: {}, // 返利信息
      deliveryInfoForm: {}, // 交付信息,
      supplierPersonList: [], // 供应商人员信息
      supplierSettlementList: [], // 结算方式
      supplierRawMaterialList: [], // 原材料信息
    }
  },
  computed: {
    isQualifiedSupplier () {
      return this.supplierClassify == '40332'
    },
    isView () {
      return this.planInfo.type == 'view'
    },
    title () {
      return this.id ? '修改考察报告' : '录入考察报告';
    },
    showBasicInfo () {
      return this.filterFiles(BASIC_INFO_FIELDS).length;
    },
    showProductionInfo () {
      return this.filterFiles(PRODUCTION_INFO_FIELDS).length;
    },
    showProducInfo () {
      return this.filterFiles(PRODUCT_INFO_FIELDS).length;
    },
    showManagementInfo () {
      return this.filterFiles(MANAGEMENT_INFO_FIELDS).length;
    },
    // 合同信息
    showBillingInfo () {
      return this.filterFiles(CONTRACT_BILLING_INFO_FIELDS).length;
    },
    showFinancialInfo () {
      return this.filterFiles(CONTRACT_FINANCIAL_INFO_FIELDS).length;
    },
    showQualityInfo () {
      return this.filterFiles(CONTRACT_QUALITY_INFO_FIELDS).length;
    },
    showRebateInfo () {
      return this.filterFiles(CONTRACT_REBATE_INFO_FIELDS).length;
    },
    showDeliveryInfo () {
      return this.filterFiles(CONTRACT_DELIVERY_INFO_FIELDS).length;
    },
  },
  watch: {
    managementInfoForm: {
      handler (val) {
        // 批量订货优惠 30 是 31否
        if (val.bulkOrderDiscount == 30) {
          MANAGEMENT_INFO_FIELDS.forEach(item => {
            if (item.prop == 'bulkOrderDiscountRemark') {
              item.required = true
            }
          })
        }
        if (val.bulkOrderDiscount == 31) {
          MANAGEMENT_INFO_FIELDS.forEach(item => {
            if (item.prop == 'bulkOrderDiscountRemark') {
              item.required = false
            }
          })
        }
      },
      immediate: true,
      deep: true
    },
    rebateInfoForm: {
      handler (val) {
        // 是否返利 必填禁用逻辑  30 是 31 否
        if (val.rebate == 31) {
          CONTRACT_REBATE_INFO_FIELDS.forEach((item) => {
            if (item.prop != 'rebate') {
              item.disabled = true
              item.required = false
            }
          })
        }
        if (val.rebate == 30) {
          CONTRACT_REBATE_INFO_FIELDS.forEach((item) => {
            if (item.prop != 'rebate') {
              item.disabled = false
              item.required = true
            }
          })
        }
      },
      immediate: true,
      deep: true
    },
    productInfoForm: {
      handler (val) {
        if (val.marketValue == 31) {
          PRODUCT_INFO_FIELDS.forEach((item) => {
            if (item.prop == 'marketValueRemark') {
              item.required = false
            }
          })
        }
        if (val.marketValue == 30) {
          PRODUCT_INFO_FIELDS.forEach((item) => {
            if (item.prop == 'marketValueRemark') {
              item.required = true
            }
          })
        }
      },
      immediate: true,
      deep: true
    },
    supplierSettlementList: {
      handler (val) {
        const settlementTypeList = val.map(item => item.settlementType)
        // 商业承兑 40919 信用凭证 40920 银行承兑 40921 转账 40922 现金 40923
        if (settlementTypeList.includes(40919) || settlementTypeList.includes(40921)) {
          // 是否承兑 = 是
          this.billingMethodInfoForm.acceptInvoice = 30
        } else if (settlementTypeList.includes(40920) || settlementTypeList.includes(40922) || settlementTypeList.includes(40923)) {
          // 是否承兑 = 否
          this.billingMethodInfoForm.acceptInvoice = 31
        }
        BILLING_METHOD_FIELDS.forEach((item) => {
          if (item.prop == 'commercialAcceptanceTypeArray') {
            if (settlementTypeList.includes(40919)) {
              item.required = true
            } else {
              item.required = false
            }
          }
          if (item.prop == 'creditAcceptanceType') {
            if (settlementTypeList.includes(40920)) {
              item.required = true
            } else {
              item.required = false
            }
          }
        })
      },
      immediate: true,
      deep: true
    },
    // 结算方式
    billingMethodInfoForm: {
      handler (val) {
        BILLING_METHOD_FIELDS.forEach(item => {
          if (item.prop == 'acceptBankRequire') {
            if (val.acceptInvoice == 30) {
              item.required = true
            } else if (val.acceptInvoice == 31) {
              item.required = false
            }
          }
          if (item.prop == 'acceptBankRequireRemark') {
            if (val.acceptBankRequire == 1108) {
              item.required = true
            } else if (val.acceptBankRequire == 1109) {
              item.required = false
            }
          }
        })
      },
      immediate: true,
      deep: true
    },
    // 结算信息
    billingInfoForm: {
      handler (val) {
        // 结账时间
        /* 结算时间为非固定结账日时：则付款方式与结账区间，都可以选择 40289
            结算时间为固定结账日时：则付款方式，仅可以选择【货到付款、票到付款】
            结账区间不可以选择：【0 1102、5 1101、65 40747】 */
        if (val.checkoutTime != 40289) {
          CONTRACT_BILLING_INFO_FIELDS.forEach(item => {
            if (item.prop == 'paidType') {
              item.options.forEach(ele => {
                if (ele.sysTypeId != 40296 && ele.sysTypeId != 40297) {
                  ele.disabled = true;
                }
              })
            }
            if (item.prop == 'checkoutRange') {
              item.options.forEach(ele => {
                if (ele.sysTypeId == 1102 || ele.sysTypeId == 1101 || ele.sysTypeId == 40747) {
                  ele.disabled = true;
                }
              })
            }
          })
        }
        if (val.checkoutTime == 40289) {
          CONTRACT_BILLING_INFO_FIELDS.forEach(item => {
            if (item.prop == 'paidType') {
              item.options.forEach(ele => {
                ele.disabled = false;
              })
            }
            if (item.prop == 'checkoutRange') {
              item.options.forEach(ele => {
                ele.disabled = false;
              })
            }
          })
        }
        // 结算方式 40 银行承兑 41 现金 896 转账 40290 商业承兑 40291 转账+银行承兑 40292 转账+商业承兑 40293 银行承兑+商业承兑
        // 银行承兑
        if (val.settlementType == 40 || val.settlementType == 40291) {
          CONTRACT_BILLING_INFO_FIELDS.forEach((item) => {
            if (item.prop == 'acceptPeriod') {
              item.required = true
            }
            if (item.prop == 'commercialAcceptancePeriod') {
              item.required = false
            }
          })
        } else if (val.settlementType == 40290 || val.settlementType == 40292) {
          CONTRACT_BILLING_INFO_FIELDS.forEach((item) => {
            if (item.prop == 'commercialAcceptancePeriod') {
              item.required = true
            }
            if (item.prop == 'acceptPeriod') {
              item.required = false
            }
          })
        } else if (val.settlementType == 40293) {
          CONTRACT_BILLING_INFO_FIELDS.forEach((item) => {
            if (item.prop == 'acceptPeriod' || item.prop == 'commercialAcceptancePeriod') {
              item.required = true
            }
          })
        } else {
          CONTRACT_BILLING_INFO_FIELDS.forEach((item) => {
            if (item.prop == 'acceptPeriod' || item.prop == 'commercialAcceptancePeriod') {
              item.required = false
            }
          })
        }
        let settlementArr = ['acceptRatio', 'acceptMoney'] // 承兑比例 承兑金额(万元)
        let settlementArr1 = ['acceptPeriod'] // 承兑期限(月)
        if (val.settlementType == 41 || val.settlementType == 896) {
          this.billingInfoForm.acceptInvoice = 31 // 否
        } else {
          this.billingInfoForm.acceptInvoice = 30 // 是
        }
        // [40291, 40292] 可编辑
        if ([40291, 40292].includes(val.settlementType)) {
          CONTRACT_BILLING_INFO_FIELDS.forEach((item) => {
            if (settlementArr.concat(settlementArr1).includes(item.prop)) {
              item.disabled = false
            }
          })
        }
        if ([41, 896].includes(val.settlementType)) {
          CONTRACT_BILLING_INFO_FIELDS.forEach((item) => {
            if (settlementArr.concat(settlementArr1).includes(item.prop)) {
              item.disabled = true
            }
          })
        }
        if ([40290].includes(val.settlementType)) {
          CONTRACT_BILLING_INFO_FIELDS.forEach((item) => {
            if (settlementArr.includes(item.prop)) {
              item.disabled = false
            }
            if (settlementArr1.includes(item.prop)) {
              item.disabled = true
            }
          })
        }
        if ([40293].includes(val.settlementType)) {
          CONTRACT_BILLING_INFO_FIELDS.forEach((item) => {
            if (settlementArr.includes(item.prop)) {
              item.disabled = true
            }
            if (settlementArr1.includes(item.prop)) {
              item.disabled = false
            }
          })
        }
        // 结账区间为0时 税票提供时间
        if (val.checkoutRange == 1101) {
          CONTRACT_BILLING_INFO_FIELDS.forEach(item => {
            if (item.prop == 'taxBillProvideTime') {
              item.disabled = false
            }
          })
        }
        // 101 普通发票 102 增值税专用发票 103 无税票
        let invoiceInfoArr = ['taxBillRate1', 'taxBillRate2', 'taxBillProvideTime']
        let invoiceInfoArr1 = ['miniInvoiceMoney']
        if (val.invoiceType == 101) {
          CONTRACT_BILLING_INFO_FIELDS.forEach((item) => {
            if (invoiceInfoArr.includes(item.prop)) {
              item.disabled = true
            }
            if (invoiceInfoArr1.includes(item.prop)) {
              item.disabled = false
            }
          })
        }
        if (val.invoiceType == 102) {
          CONTRACT_BILLING_INFO_FIELDS.forEach((item) => {
            if (invoiceInfoArr.concat(invoiceInfoArr1).includes(item.prop)) {
              item.disabled = false
            }
          })
        }
        if (val.invoiceType == 103) {
          CONTRACT_BILLING_INFO_FIELDS.forEach((item) => {
            if (invoiceInfoArr.concat(invoiceInfoArr1).includes(item.prop)) {
              item.disabled = true
            }
          })
        }
        // 结账区间为0时 税票提供时间
        if (val.checkoutRange != 1101) {
          CONTRACT_BILLING_INFO_FIELDS.forEach(item => {
            if (item.prop == 'taxBillProvideTime') {
              item.disabled = true
            }
          })
        }
        // 银行承兑 商业承兑  银行承兑+商业承兑
        if ([40, 40290, 40293].includes(val.settlementType)) {
          CONTRACT_BILLING_INFO_FIELDS.forEach((item) => {
            if (item.prop == 'acceptRatio') {
              item.disabled = true
            }
            if (item.prop == 'acceptMoney') {
              item.required = false
            }
          })
        }
        // 税票提供时间 40287 结账前 40288 结账后
        if (val.taxBillProvideTime == 40287) {
          CONTRACT_BILLING_INFO_FIELDS.forEach((item) => {
            if (item.prop == 'taxBillMoneyLimit' || item.prop == 'taxBillTimeLimit') {
              item.required = false
            }
          })
        }
        if (val.taxBillProvideTime == 40288) {
          CONTRACT_BILLING_INFO_FIELDS.forEach((item) => {
            if (item.prop == 'taxBillMoneyLimit' || item.prop == 'taxBillTimeLimit') {
              item.required = true
            }
          })
        }
        // 是否集中结账 否集中
        if (val.centralizedSettle == 31) {
          CONTRACT_BILLING_INFO_FIELDS.forEach((item) => {
            if (item.prop == 'centralizedSettlePlace') {
              item.required = false
              item.disabled = true
            }
          })
        }
        // 是集中
        if (val.centralizedSettle == 30) {
          CONTRACT_BILLING_INFO_FIELDS.forEach((item) => {
            if (item.prop == 'centralizedSettlePlace') {
              item.required = true
              item.disabled = false
            }
          })
        }
      },
      immediate: true,
      deep: true
    },
    // 财务信息监听
    financialInfoForm: {
      handler (val) {
        if (!val.priceBaseOnRawMaterial) {
          val.priceBaseOnRawMaterial = 2
        }
        // 约定价格是否依据原材料进行公式核算 1是 2否
        const priceBaseFiles = [ 'rawMaterialPriceRef', 'rawMaterialPriceFloatRate', 'goodsName', 'goodsPriceFloatRate', 'coreRawMaterialName', 'purchaseAddRatio', ]
        if (val.priceBaseOnRawMaterial == 1) {
          CONTRACT_FINANCIAL_INFO_FIELDS.forEach((item) => {
            if (priceBaseFiles.includes(item.prop)) {
              item.disabled = false
              item.required = true
            }
          })
        }
        if (val.priceBaseOnRawMaterial == 2 || !val.priceBaseOnRawMaterial) {
          CONTRACT_FINANCIAL_INFO_FIELDS.forEach((item) => {
            if (priceBaseFiles.includes(item.prop)) {
              item.disabled = true
              item.required = false
            }
          })
        }
        // 是否库存报价 30 是 31 否
        if (val.stockInsurance == 30) {
          CONTRACT_FINANCIAL_INFO_FIELDS.forEach((item) => {
            if (item.prop == 'stockInsuranceRemark') {
              item.required = true
            }
          })
        }
        // 是否库存报价 30 是 31 否
        if (val.stockInsurance == 31) {
          CONTRACT_FINANCIAL_INFO_FIELDS.forEach((item) => {
            if (item.prop == 'stockInsuranceRemark') {
              item.required = false
            }
          })
        }
      },
      immediate: true,
      deep: true
    },
    // 铺底质保信息
    qualityInfoForm: {
      handler (val) {
        // 铺底资金
        if (val.initialCapital == 0) {
          CONTRACT_QUALITY_INFO_FIELDS.forEach((item) => {
            if (item.prop == 'initialCapitalCollectType') {
              item.disabled = true
              item.required = false
            }
          })
        }
        if (val.initialCapital > 0) {
          CONTRACT_QUALITY_INFO_FIELDS.forEach((item) => {
            if (item.prop == 'initialCapitalCollectType' || item.prop == 'etcQaExecuteArea') {
              item.disabled = false
              item.required = true
            }
          })
        }
        // 质量保证金
        if (val.retentionMoney == 0) {
          CONTRACT_QUALITY_INFO_FIELDS.forEach((item) => {
            if (item.prop == 'retentionMoneyCollectType') {
              item.disabled = true
              item.required = false
            }
          })
        }
        if (val.retentionMoney > 0) {
          CONTRACT_QUALITY_INFO_FIELDS.forEach((item) => {
            if (item.prop == 'retentionMoneyCollectType' || item.prop == 'etcQaExecuteArea') {
              item.disabled = false
              item.required = true
            }
          })
        }
        if (val.retentionMoney == 0 && val.initialCapital == 0) {
          CONTRACT_QUALITY_INFO_FIELDS.forEach((item) => {
            if (item.prop == 'etcQaExecuteArea') {
              item.disabled = true
              item.required = false
            }
          })
        }
      },
      immediate: true,
      deep: true
    },
    isQualifiedSupplier: {
      handler (val) {
        if (val) {
          const fiels = ['coreRawMaterialName', 'goodsPriceFloatRate', 'goodsName', 'rawMaterialPriceFloatRate', 'rawMaterialPriceRef']
          this.CONTRACT_FINANCIAL_INFO_FIELDS = _.cloneDeep(CONTRACT_FINANCIAL_INFO_FIELDS).filter(item => !fiels.includes(item.prop))
        }
      }
    }
  },
  created () {
    const { planId, supplierId, targetList, type, supplierClassify } = this.$route.query;
    this.planInfo = {
      planId,
      supplierId,
      targetList,
      type
    }
    if (this.planInfo.planId) {
      this.getDetailData()
    } else {
      this.initItemOptions(supplierClassify)
    }
    this.initTabName()
  },
  methods: {
    initTabName () {
      // ['基本信息', '人员信息', '商品信息', '管理信息', '合同信息']
      if (this.showBasicInfo || this.showProductionInfo) {
        this.activateName = this.tabList[0]
      } else if (this.showProducInfo) {
        this.activateName = this.tabList[2]
      } else if (this.showManagementInfo) {
        this.activateName = this.tabList[3]
      } else if (this.showBillingInfo || this.showFinancialInfo || this.showQualityInfo || this.showRebateInfo || this.showDeliveryInfo) {
        this.activateName = this.tabList[4]
      }
    },
    // 初始化 options
    initItemOptions (supplierClassify) {
      // 后续待办
      // 1:'潜在转合格 2:'合格转潜在' 3:'潜在转线索' 4:'供应商淘汰' 5:'供应商拉黑'
      // 6:'修改资质' 7:'修改登记表信息' 8: 签订合同 9:增加供货信息 10:价格调整
      queryTodoTypeservice().then(res => {
        if (res && res.result && res.result.length) {
          const todoTypes = res.result.map(item => ({
            value: item.subsequentBacklog,
            label: item.subsequentBacklogName
          }))
          let typeList = []
          // 合格供应商
          if (supplierClassify == 40332) {
            typeList = todoTypes.filter(item => !['1', '3'].includes(item.value))
          }
          // 潜在供应商
          if (supplierClassify == 40331) {
            typeList = todoTypes.filter(item => !['2', '9', '10'].includes(item.value))
          }
          // 线索供应商
          if (supplierClassify == 40899) {
            typeList = todoTypes.filter(item => ['4', '5', '7'].includes(item.value))
          }
          const { subsequentBacklog } = this.baseInfoForm
          if (subsequentBacklog && subsequentBacklog.length > 0) {
            typeList.map(item => {
              item.disabled = (subsequentBacklog.includes('1') && !['1', '7', '8'].includes(item.value)) ||
              (subsequentBacklog.includes('2') && !['2', '7', '8'].includes(item.value)) ||
              (subsequentBacklog.includes('3') && !['3'].includes(item.value)) ||
              (subsequentBacklog.includes('4') && !['4'].includes(item.value)) ||
              (subsequentBacklog.includes('5') && !['5'].includes(item.value)) ||
              (subsequentBacklog.includes('6') && !['6', '9', '10'].includes(item.value)) ||
              (subsequentBacklog.includes('7') && !['7', '1', '2', '9', '10'].includes(item.value)) ||
              (subsequentBacklog.includes('8') && !['8', '1', '2', '9', '10'].includes(item.value)) ||
              (subsequentBacklog.includes('9') && ['9', '2', '3'].includes(item.value)) ||
              (subsequentBacklog.includes('10') && ['10', '2', '3'].includes(item.value))
            })
          }
          console.log(subsequentBacklog)
          console.log(typeList)
          BASE_INFO_FIELDS.forEach(item => {
            if (item.prop == 'subsequentBacklog') {
              item.options = typeList
            }
          })
        }
      })
      let files = [
        ...this.filterFiles(BASIC_INFO_FIELDS),
        ...this.filterFiles(PRODUCT_INFO_FIELDS),
        ...this.filterFiles(MANAGEMENT_INFO_FIELDS),
        ...this.filterFiles(CONTRACT_BILLING_INFO_FIELDS),
        ...this.filterFiles(BILLING_METHOD_FIELDS),
        ...this.filterFiles(CONTRACT_FINANCIAL_INFO_FIELDS),
        ...this.filterFiles(CONTRACT_QUALITY_INFO_FIELDS),
        ...this.filterFiles(CONTRACT_REBATE_INFO_FIELDS),
        ...this.filterFiles(CONTRACT_DELIVERY_INFO_FIELDS),
      ]
      let masterIds = []
      let otherIds = []
      files.map((item) => {
        if (item.dictId && item.isMaster && !masterIds.includes(item.dictId)) {
          masterIds.push(item.dictId)
        } else if (item.dictId && !item.isMaster && !otherIds.includes(item.dictId)) {
          otherIds.push(item.dictId)
        }
      })
      Promise.all([
        this.queryOptionsByMaster(masterIds),
        this.queryOptionsBySupply(otherIds),
        this.queryManageAreaList()
      ]).then(([masterData, supplyData, manageAreaData]) => {
        const filesObj = Object.assign({}, masterData, supplyData, manageAreaData)
        files.forEach((item) => {
          if (item.dictId) {
            Object.keys(filesObj).forEach((ele) => {
              if (item.dictId == ele) {
                item.options = filesObj[ele]
              }
            })
          }
        })
      }).catch(() => {
      })
    },
    // 通过主数据获取
    async queryOptionsByMaster (ids) {
      const { result } = await querySysTypeByDictIdsService({ itemIds: ids.join(',') })
      // 禁用信用凭证相关选项
      if (result[16]) {
        const disabledList = [40904, 40905, 40906, 40907]
        result[16].forEach(item => {
          if (disabledList.includes(item.sysTypeId)) {
            item.disabled = true;
          }
        })
      }
      return result;
    },
    // 通过供应商获取
    async queryOptionsBySupply (ids) {
      const { result } = await queryItemsByDictIdsService(ids)
      return result;
    },
    // 获取管理区域
    async queryManageAreaList () {
      const { result } = await queryManageAreaService()
      if (result) {
        return {
          10000: result.map(item => ({ manageAreaId: Number(item.manageAreaId), manageAreaName: item.manageAreaName })),
          10001: result.filter(item => item.manageAreaName != '集团总部')
        }
      }
    },
    // 根据考察目的过滤Tab信息
    filterFiles (files) {
      const { targetList } = this.planInfo;
      if (targetList.length) {
        return files.filter(item => targetList.includes(item.target) || !item.target)
      }
    },
    // 获取报告详情
    getDetailData () {
      queryReportDetailService({ ...this.planInfo }).then((res) => {
        if (isResponseSuccess(res)) {
          const { result } = res;
          if (result) {
            this.reportId = result.reportId;
            this.supplierClassify = result.supplierClassify;
            if (result.supplier || result.supplierContract || result.supplierPersonList) {
              const {
                visitTime, negotiationDetail, inspectCompleteTime, disposalMeasures,
                subsequentBacklog, backlogExplain, planCompleteTime, supplier,
                supplierContract, supplierPersonList, supplierSettlementList, supplierRawMaterialList,
              } = result;
              this.baseInfoForm = {
                visitTime,
                negotiationDetail,
                inspectCompleteTime,
                disposalMeasures,
                subsequentBacklog,
                backlogExplain,
                planCompleteTime,
              }
              let formData = {
                supplier: supplier ? JSON.parse(supplier) : {},
                supplierContract: supplierContract ? JSON.parse(supplierContract) : {},
                supplierPersonList: supplierPersonList ? JSON.parse(supplierPersonList) : [],
                supplierSettlementList: supplierSettlementList ? JSON.parse(supplierSettlementList) : [],
                supplierRawMaterialList: supplierRawMaterialList ? JSON.parse(supplierRawMaterialList) : [],
              }
              console.log(formData)
              this.handleFillFormData(formData)
            } else {
              this.getSupplieDetailData()
            }
          } else {
            this.getSupplieDetailData()
          }
        }
        this.initItemOptions(this.supplierClassify)
      })
    },
    // 获取供应商详情
    getSupplieDetailData () {
      querySupplierDetailService({ supplierId: this.planInfo.supplierId }).then((res) => {
        if (isResponseSuccess(res)) {
          const { result } = res
          result.supplier.supplierManageCategoryList = result.supplierManageCategoryList.map((item) => ({
            categoryName: item.manageCategory,
            categoryNo: item.manageCategoryCode,
            categoryUuid: item.manageCategoryId,
          }));
          if (result.supplierContract && result.supplierContract.etcQaExecuteArea) {
            result.supplierContract.etcQaExecuteArea = result.supplierContract.etcQaExecuteArea.split(',')
          }
          this.handleFillFormData(result)
        }
      })
    },
    // 表单数据回填
    handleFillFormData (result) {
      const { supplier, supplierContract, supplierPersonList, supplierSettlementList, supplierRawMaterialList } = result;
      // 供应商人员信息
      this.supplierPersonList = supplierPersonList;
      // 基础信息
      this.basicInfoForm = Object.assign({}, this.basicInfoForm, { ...this.filterObjKeys(supplier, BASIC_INFO_FIELDS) })
      // 生产信息
      this.productionInfoForm = Object.assign({}, this.productionInfoForm, { ...this.filterObjKeys(supplier, PRODUCTION_INFO_FIELDS) })
      // 商品信息
      this.productInfoForm = Object.assign({}, this.productInfoForm, { ...this.filterObjKeys(supplier, PRODUCT_INFO_FIELDS) })
      // 管理信息
      this.managementInfoForm = Object.assign({}, this.managementInfoForm, { ...this.filterObjKeys(supplier, MANAGEMENT_INFO_FIELDS) })
      // 结算信息
      this.billingInfoForm = Object.assign({}, this.billingInfoForm, { ...this.filterObjKeys(supplierContract, CONTRACT_BILLING_INFO_FIELDS) })
      this.billingMethodInfoForm = Object.assign({}, this.billingMethodInfoForm, { ...this.filterObjKeys(supplierContract, BILLING_METHOD_FIELDS) })
      // 结算方式
      this.supplierSettlementList = supplierSettlementList || [];
      // 原材料信息
      this.supplierRawMaterialList = supplierRawMaterialList || [];
      // 财务信息
      this.financialInfoForm = Object.assign({}, this.financialInfoForm, { ...this.filterObjKeys(supplierContract, CONTRACT_FINANCIAL_INFO_FIELDS) })
      // 铺底质保信息
      this.qualityInfoForm = Object.assign({}, this.qualityInfoForm, { ...this.filterObjKeys(supplierContract, CONTRACT_QUALITY_INFO_FIELDS) })
      // 返利信息
      this.rebateInfoForm = Object.assign({}, this.rebateInfoForm, { ...this.filterObjKeys(supplierContract, CONTRACT_REBATE_INFO_FIELDS) })
      // 交付信息
      this.deliveryInfoForm = Object.assign({}, this.deliveryInfoForm, { ...this.filterObjKeys(supplierContract, CONTRACT_DELIVERY_INFO_FIELDS) })
    },
    getTimeStamp (str) {
      return new Date(str).getTime()
    },
    // 提交校验
    handleValidSubmit (isSubmit) {
      const { visitTime, inspectCompleteTime } = this.baseInfoForm
      if (this.getTimeStamp(visitTime) > this.getTimeStamp(inspectCompleteTime)) {
        return this.$message.warning('拜访时间不能大于完成时间')
      }
      let hasEmptyVal = false;
      let hasMainContactPerson = false;
      if (this.$refs.supplyUserInfo) {
        const supplierDTOList = this.$refs.supplyUserInfo.supplierDTOList;
        if (supplierDTOList.length) {
          hasEmptyVal = supplierDTOList.some((item) =>
            !item.personName || !item.personSex ||
            !item.personPost || !item.personRole || !item.contactPhone
          )
          hasMainContactPerson = supplierDTOList.some((item) => item.personRole == 2)
        } else {
          hasEmptyVal = true;
        }
      }
      if (this.$refs.supplyUserInfo && hasEmptyVal) {
        return this.$message.warning('人员信息填写不完整')
      }
      if (this.$refs.supplyUserInfo && !hasMainContactPerson) {
        return this.$message.warning('人员信息缺少主要联系人信息')
      }
      if (this.hasManageCategory() && (!this.productInfoForm.supplierManageCategoryList || this.productInfoForm.supplierManageCategoryList.length == 0)) {
        return this.$message.warning('商品信息下的经营品类不能为空')
      }
      if (this.$refs.billingMethodList && this.$refs.billingMethodList.getValidate()) {
        return;
      }
      if (this.$refs.rawMaterialInfo && this.$refs.rawMaterialInfo.getValidate()) {
        return;
      }
      try {
        Promise.all([
          this.$refs.baseInfoForm ? this.$refs.baseInfoForm.$refs['base-info-form'].validate() : null,
          this.$refs.basicInfoForm ? this.$refs.basicInfoForm.$refs['basic-info-form'].validate() : null,
          this.$refs.productionInfoForm ? this.$refs.productionInfoForm.$refs['production-info-form'].validate() : null,
          this.$refs.productInfoForm ? this.$refs.productInfoForm.$refs['product-info-form'].validate() : null,
          this.$refs.managementInfoForm ? this.$refs.managementInfoForm.$refs['management-info-form'].validate() : null,
          this.$refs.billingInfoForm ? this.$refs.billingInfoForm.$refs['billing-info-form'].validate() : null,
          this.$refs.billingMethodInfoForm ? this.$refs.billingMethodInfoForm.$refs['billing-method-info-form'].validate() : null,
          this.$refs.financialInfoForm ? this.$refs.financialInfoForm.$refs['financial-info-form'].validate() : null,
          this.$refs.qualityInfoForm ? this.$refs.qualityInfoForm.$refs['quality-info-form'].validate() : null,
          this.$refs.rebateInfoForm ? this.$refs.rebateInfoForm.$refs['rebate-info-form'].validate() : null,
          this.$refs.deliveryInfoForm ? this.$refs.deliveryInfoForm.$refs['delivery-info-form'].validate() : null,
        ]).then((res) => {
          this.handleSubmit(isSubmit)
        }).catch(() => {
          return this.$message.warning('信息填写不完整')
        })
      } catch (error) {
        return this.$message.warning('信息填写不完整')
      }
    },
    // 是否存在经营品类
    hasManageCategory () {
      return this.planInfo.targetList.includes(1)
    },
    // 格式化入参
    formatParams () {
      if (this.hasManageCategory() && this.productInfoForm.supplierManageCategoryList) {
        this.productInfoForm.supplierManageCategoryList.forEach(item => {
          item.manageCategory = item.categoryName
          item.manageCategoryCode = item.categoryNo
          item.manageCategoryId = item.categoryUuid
        })
      }
      const params = {
        supplierId: this.planInfo.supplierId,
        id: this.reportId,
        ...this.baseInfoForm,
        supplier: JSON.stringify({ ...this.basicInfoForm, ...this.productionInfoForm, ...this.productInfoForm, ...this.managementInfoForm, }), // 供应商基本信息 管理信息 商品信息
        supplierContract: JSON.stringify({ ...this.billingInfoForm, ...this.billingMethodInfoForm, ...this.financialInfoForm, ...this.qualityInfoForm, ...this.rebateInfoForm, ...this.deliveryInfoForm, }), // 供应商合同信息
        supplierPersonList: this.$refs.supplyUserInfo ? JSON.stringify(this.$refs.supplyUserInfo.supplierDTOList) : null, // 人员信息
        supplierManageCategoryList: this.hasManageCategory() ? JSON.stringify(this.productInfoForm.supplierManageCategoryList) : null,
        supplierSettlementList: this.$refs.billingMethodList ? JSON.stringify(this.supplierSettlementList) : null,
        supplierRawMaterialList: this.$refs.rawMaterialInfo ? JSON.stringify(this.supplierRawMaterialList) : null
      }
      return params;
    },
    // 暂存
    async handleSubmit (isSubmit) {
      if (isSubmit) {
        const res = await addReportService(
          this.formatParams(),
          state => { this.submitLoading = state }
        )
        if (res) {
          this.$message.success(res.message);
          this.handleCancel()
        }
      } else {
        const res = await stashReportService(
          this.formatParams(),
          state => { this.submitLoading = state }
        )
        if (res) {
          this.$message.success(res.message);
          this.handleCancel()
        }
      }
    },
    // 取消
    handleCancel () {
      this.$router.go(-1);
    },
    // 过滤对象中指定的key
    filterObjKeys (obj, fileObj) {
      let keys = this.filterFiles(fileObj).map((item) => item.prop);
      return Object.keys(obj).reduce((newData, key) => {
        if (keys.includes(key)) {
          newData[key] = obj[key];
        }
        return newData;
      }, {});
    },
    // 结算方式回调
    handleChange (data) {
      const { prop, value } = data;
      if (prop === 'supplierSettlementList') {
        // 结算方式 变更
        this.supplierSettlementList = value
      }
      if (prop === 'supplierRawMaterialList') {
        // 结算方式 变更
        this.supplierRawMaterialList = value
      }
    }
  }
};
</script>
<style scoped>
.formFooter {
  margin-top: 10px;
}
</style>
